const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 重写请求
function myRequest(url, data=false, callback, badCall=false, failCall=false, showLoading=true){
  var that = this;
  var method = 'GET';
  if (data){
    method = 'POST';
    console.log('post data:');
    console.log(data);
  }

  if (showLoading){
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
  }

  console.log('requestUrl:');
  console.log(url);

  wx.request({
    url: url,
    data: data,
    method: method,
    success(res) {
      console.log(res.data);
      if (res.data.code == 1){
        callback(res.data);
      }else{
        console.log('err msg:')
        if (res.data.msg){
          delayedToast(res.data.msg);
        }else{
          delayedToast('糟糕！系统错误😰');
        }

        if (badCall){
          callback(res.data);
        }
      }
    },
    fail(e){
      console.log(e);
      delayedToast('糟糕！系统错误😰');
      if (failCall) {
        callback(false);
      }
    },
    complete(){
      wx.hideLoading();
    }
  })
}

function delayedToast(content){
  setTimeout(function(){
    wx.showToast({
      title: content,
      icon: 'none',
      duration: 2000,
      mask: true,
    });
  }, 200);
}

// 验证手机号
function isPoneAvailable(str) {
  var myreg = /^1\d{10}$/;

  if (!myreg.test(str)) {
    return false;
  } else {
    return true;
  }
}

module.exports = {
  formatTime: formatTime,
  myRequest: myRequest,
  isPoneAvailable: isPoneAvailable,
}

